package leetcode.code1583;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
		int[][] closes = new int[n][n];
		for (int i = 0; i < n; i++) {
			int[] prefer = preferences[i];
			for (int j = 0; j < n - 1; j++) {
				closes[i][prefer[j]] = n - j;
			}
		}
		int ans = 0;
		int size = n >> 1;
		boolean[] flag = new boolean[n];
		for (int i = 0; i < size; i++) {
			int[] pairi = pairs[i];
			int x = pairi[0], y = pairi[1];
			int xy = closes[x][y], yx = closes[y][x];
			for (int j = i + 1; j < size; j++) {
				int[] pairj = pairs[j];
				int u = pairj[0], v = pairj[1];
				int uv = closes[u][v], vu = closes[v][u];
				int xu = closes[x][u], xv = closes[x][v];
				int yu = closes[y][u], yv = closes[y][v];
				int ux = closes[u][x], uy = closes[u][y];
				int vx = closes[v][x], vy = closes[v][y];
				if (xu > xy && ux > uv) {
					if (!flag[x]) {
						flag[x] = true;
						ans++;
					}
					if (!flag[u]) {
						flag[u] = true;
						ans++;
					}
				}
				if (xv > xy && vx > vu) {
					if (!flag[x]) {
						flag[x] = true;
						ans++;
					}
					if (!flag[v]) {
						flag[v] = true;
						ans++;
					}
				}
				if (yu > yx && uy > uv) {
					if (!flag[y]) {
						flag[y] = true;
						ans++;
					}
					if (!flag[u]) {
						flag[u] = true;
						ans++;
					}
				}
				if (yv > yx && vy > vu) {
					if (!flag[y]) {
						flag[y] = true;
						ans++;
					}
					if (!flag[v]) {
						flag[v] = true;
						ans++;
					}
				}
			}
		}
		return ans;
	}

//	6
//	[[1,4,3,2,5],[0,5,4,3,2],[3,0,1,5,4],[2,1,4,0,5],[2,1,0,3,5],[3,4,2,0,1]]
//	[[3,1],[2,0],[5,4]]

	@Override
	public void debug1() {
		HelpDebug.compare(2, this.unhappyFriends(4, HelpDebug.str2array1("[[1,2,3],[3,2,0],[3,1,0],[1,2,0]]"),
				HelpDebug.str2array1("[[0,1],[2,3]]")));
	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
